<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\facade\Validate;

class Admin extends Controller
{
    // 管理员列表
    public function adminList()
    {
        if (request()->isPost()) {
            $data = [
                'limit' => input('limit', 0),
                'phone' => input('phone')
            ];
            $where = [];
            if ($data['phone']) {
                $where[] = ['phone', 'like', '%' . $data['phone'] . '%'];
            }
            $adminList = model('Admin')->where($where)->order(['create_time' => 'asc'])->withAttr([
                'role' => function ($value, $info) {
                    $groupId = model('AuthGroupAccess')->where(['uid' => $info['id']])->value('group_id');
                    $role = model('AuthGroup')->where(['id' => $groupId])->value('title');
                    return $role;
                }
            ])->paginate($data['limit'], false, ['query' => $data])->append(['role']);
            $this->result(['admin_list' => $adminList->items(), 'count' => $adminList->total()], 0, '获取管理员成功', 'json');
        }
        return view();
    }

    // 管理员状态切换
    public function setAdminStatus()
    {
        $data = [
            'id' => input('id'),
            'status' => input('status')
        ];
        if ($data['id'] == config('extra.super_admin')) {
            $this->error('超级管理员不允许禁用');
        }
        $result = model('Admin')->isUpdate(true)->save($data);
        if ($result) {
            $this->success('操作成功');
        } else {
            $this->error('网络问题，请稍后再试');
        }
    }

    // 管理员编辑
    public function editAdmin()
    {
        if (request()->isAjax()) {
            $data = [
                'id' => input('id'),
                'name' => input('name'),
                'password' => input('password'),
                'phone' => input('phone'),
                'qq' => input('qq'),
                'role_id' => input('role'),
                'status' => input('status', 0)
            ];
            $validate = Validate::make([
                'password|新密码' => 'length:6, 14',
                'qq|QQ' => 'number'
            ]);
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            } else {
                if (!$data['password']) {
                    unset($data['password']);
                } else {
                    $data['password'] = md5($data['password']);
                }
                Db::startTrans();
                try {
                    model('Admin')::update($data);
                    model('AuthGroupAccess')->isUpdate(true, ['uid' => $data['id']])->save(['group_id' => $data['role_id']]);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success('编辑成功');
            }
        }
        $data = [
            'id' => input('id')
        ];
        $adminInfo = model('Admin')->where($data)->withAttr([
            'role_id' => function ($value, $info) {
                $roleId = model('AuthGroupAccess')->where(['uid' => $info['id']])->value('group_id');
                return $roleId;
            },
            'role_list' => function ($value, $info) {
                $roleList = model('AuthGroup')->select();
                return $roleList;
            }
        ])->find()->append(['role_id', 'role_list']);
        $viewData = [
            'adminInfo' => $adminInfo
        ];
        $this->assign($viewData);
        return view();
    }

    // 管理员删除
    public function delAdmin()
    {
        $data = [
            'id' => input('id')
        ];
        if ($data['id'] == config('extra.super_admin')) {
            $this->error('超级管理员不允许删除');
        }
        $result = model('Admin')::destroy($data);
        if ($result) {
            $this->success('删除成功');
        } else {
            $this->error('网络问题，请稍后重试');
        }
    }

    // 管理员添加
    public function addAdmin()
    {
        if (request()->isAjax()) {
            $data = [
                'group_id' => input('role'),
                'status' => input('status', 0),
                'username' => input('username'),
                'password' => input('password'),
                'name' => input('name'),
                'phone' => input('phone'),
                'qq' => input('qq')
            ];
            $validate = Validate::make([
                'username|登录账户' => 'require|unique:admin',
                'password|密码' => 'require|length:6,14'
            ]);
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            } else {
                Db::startTrans();
                try {
                    $data['password'] = md5($data['password']);
                    $adminInfo = model('Admin')::create($data);
                    if ($data['group_id']) {
                        model('AuthGroupAccess')::create(['uid' => $adminInfo['id'], 'group_id' => $data['group_id']]);
                    }
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error('网络问题，请稍后再试');
                }
                $this->success('添加管理员成功');
            }
        }
        $roleList = model('AuthGroup')->select();
        $viewData = [
            'roleList' => $roleList
        ];
        $this->assign($viewData);
        return view();
    }

    // 角色列表
    public function roleList()
    {
        if (request()->isPost()) {
            $data = [
                'limit' => input('limit')
            ];
            $roleList = model('AuthGroup')->paginate($data['limit'], false, ['query' => $data]);
            $this->result(['data' => $roleList->items(), 'count' => $roleList->total()], 0, '', 'json');
        }
        return view();
    }

    // 编辑角色
    public function editRole()
    {
        if (request()->isAjax()) {
            $data = [
                'id' => input('id'),
                'title' => input('title'),
                'rules' => input('rules/a', [])
            ];
            $validate = Validate::make([
                'title|角色名称' => 'require|unique:auth_group'
            ]);
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            } else {
                $data['rules'] = implode(',', $data['rules']);
                $result = model('AuthGroup')->isUpdate(true)->save($data);
                if ($result) {
                    $this->success('编辑角色成功');
                } else {
                    $this->error('网络问题，请稍后再试');
                }
            }
        }
        $data = [
            'id' => input('role_id')
        ];
        $roleInfo = model('AuthGroup')->where($data)->withAttr([
            'rules' => function ($value, $info) {
                $oneRules = model('AuthRule')->where(['pid' => 0])->column('id');
                $rules = explode(',', $value);
                return implode(',', array_diff($rules, $oneRules));
            }
        ])->find();
        $oneMenuList = model('AuthRule')->field(['id', 'title'])->where('pid', 0)->order('sort')->select()->each(function ($item) {
            $item['spread'] = true;
            $item['children'] = model('AuthRule')->field(['id', 'title'])->where('pid', $item['id'])->order('sort')->select();
        });
        $viewData = [
            'roleInfo' => $roleInfo,
            'oneMenuList' => $oneMenuList
        ];
        $this->assign($viewData);
        return view();
    }

    // 删除角色
    public function delRole()
    {
        $data = [
            'id' => input('id')
        ];
        $roleAccessCount = model('AuthGroupAccess')->where(['group_id' => $data['id']])->count();
        if ($roleAccessCount) {
            $this->error('角色下有管理员，不允许删除');
        } else {
            $result = model('AuthGroup')::destroy($data);
            if ($result) {
                $this->success('删除成功');
            } else {
                $this->error('网络问题，请稍后再试');
            }
        }
    }

    // 添加角色
    public function addRole()
    {
        if (request()->isAjax()) {
            $data = [
                'title' => input('title'),
                'rules' => input('rules/a', [])
            ];
            $validate = Validate::make([
                'title|角色名称' => 'require|unique:auth_group'
            ]);
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            } else {
                $data['rules'] = implode(',', $data['rules']);
                $result = model('AuthGroup')->save($data);
                if ($result) {
                    $this->success('添加角色成功');
                } else {
                    $this->error('网络问题，请稍后再试');
                }
            }
        } else {
            $oneMenuList = model('AuthRule')->field(['id', 'title'])->where('pid', 0)->order('sort')->select()->each(function ($item) {
                $item['spread'] = true;
                $item['children'] = model('AuthRule')->field(['id', 'title'])->where('pid', $item['id'])->order('sort')->select();
            });
            $viewData = [
                'oneMenuList' => $oneMenuList
            ];
            $this->assign($viewData);
            return view();
        }
    }
}
